import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import TopNavbar from '../../../components/TopNavbar'
import ErrorBoundary from '../../../components/ErrorBoundary'
import { fetchDoctorAdviceOrders, executeDoctorAdvice } from '../../../services/ordersService'
import styles from './index.module.css'

const DoctorAdviceOrders = () => {
  const navigate = useNavigate()
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // 获取医嘱订单数据
    const fetchOrders = async () => {
      setLoading(true)
      try {
        const response = await fetchDoctorAdviceOrders()
        if (response.success) {
          setOrders(response.data)
        }
      } catch (error) {
        console.error('获取医嘱订单失败:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchOrders()
  }, [])

  const getStatusColor = (status) => {
    switch (status) {
      case '已完成':
        return '#52c41a'
      case '待执行':
        return '#1890ff'
      case '执行中':
        return '#faad14'
      case '已取消':
        return '#ff4d4f'
      default:
        return '#666'
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case '已完成':
        return '✅'
      case '待执行':
        return '⏰'
      case '执行中':
        return '🔄'
      case '已取消':
        return '❌'
      default:
        return '❓'
    }
  }

  const getAdviceTypeIcon = (type) => {
    switch (type) {
      case '用药医嘱':
        return '💊'
      case '检查医嘱':
        return '🔬'
      case '治疗医嘱':
        return '🏥'
      default:
        return '📋'
    }
  }

  const handleOrderDetail = (order) => {
    // 跳转到订单详情页面
    console.log('查看医嘱详情:', order)
    // 这里可以跳转到医嘱详情页面
  }

  const handleExecuteOrder = async (order) => {
    if (order.status === '待执行') {
      try {
        const response = await executeDoctorAdvice(order.id)
        if (response.success) {
          // 更新本地状态
          setOrders(prevOrders => 
            prevOrders.map(o => 
              o.id === order.id ? { ...o, status: '执行中' } : o
            )
          )
          alert('医嘱执行成功')
        }
      } catch (error) {
        console.error('执行医嘱失败:', error)
        alert('执行医嘱失败，请稍后重试')
      }
    }
  }

  if (loading) {
    return (
      <div className={styles.ordersPage}>
        <ErrorBoundary>
          <TopNavbar
            title="医嘱订单"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.loadingContainer}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>加载中...</div>
        </div>
      </div>
    )
  }

  if (orders.length === 0) {
    return (
      <div className={styles.ordersPage}>
        <ErrorBoundary>
          <TopNavbar
            title="医嘱订单"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.content}>
          <div className={styles.emptyState}>
            <div className={styles.emptyIcon}>💊</div>
            <div className={styles.emptyText}>暂无医嘱订单</div>
            <div className={styles.emptySubtext}>您还没有医嘱记录</div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.ordersPage}>
      <ErrorBoundary>
        <TopNavbar
          title="医嘱订单"
          showBack={true}
          onBack={() => navigate(-1)}
        />
      </ErrorBoundary>
      
      <div className={styles.content}>
        <div className={styles.ordersList}>
          {orders.map((order) => (
            <div key={order.id} className={styles.orderCard}>
              <div className={styles.orderHeader}>
                <div className={styles.orderId}>
                  医嘱号: {order.id}
                </div>
                <div 
                  className={styles.orderStatus}
                  style={{ color: getStatusColor(order.status) }}
                >
                  {getStatusIcon(order.status)} {order.status}
                </div>
              </div>
              
              <div className={styles.orderInfo}>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>患者姓名:</span>
                  <span className={styles.infoValue}>{order.patientName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>科室:</span>
                  <span className={styles.infoValue}>{order.department}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医生:</span>
                  <span className={styles.infoValue}>{order.doctorName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医嘱日期:</span>
                  <span className={styles.infoValue}>{order.adviceDate}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医嘱类型:</span>
                  <span className={styles.infoValue}>
                    {getAdviceTypeIcon(order.adviceType)} {order.adviceType}
                  </span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医嘱内容:</span>
                  <span className={styles.infoValue}>{order.description}</span>
                </div>
                {order.medicines && order.medicines.length > 0 && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>药品:</span>
                    <span className={styles.infoValue}>{order.medicines.join(', ')}</span>
                  </div>
                )}
                {order.dosage && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>用法用量:</span>
                    <span className={styles.infoValue}>{order.dosage}</span>
                  </div>
                )}
                {order.duration && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>疗程:</span>
                    <span className={styles.infoValue}>{order.duration}</span>
                  </div>
                )}
                {order.preparation && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>准备事项:</span>
                    <span className={styles.infoValue}>{order.preparation}</span>
                  </div>
                )}
                {order.location && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>检查地点:</span>
                    <span className={styles.infoValue}>{order.location}</span>
                  </div>
                )}
                {order.treatmentPlan && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>治疗方案:</span>
                    <span className={styles.infoValue}>{order.treatmentPlan}</span>
                  </div>
                )}
                {order.frequency && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>频次:</span>
                    <span className={styles.infoValue}>{order.frequency}</span>
                  </div>
                )}
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>费用:</span>
                  <span className={styles.infoValue}>¥{order.fee}</span>
                </div>
                {order.notes && (
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>注意事项:</span>
                    <span className={styles.infoValue}>{order.notes}</span>
                  </div>
                )}
              </div>
              
              <div className={styles.orderActions}>
                <button 
                  className={styles.actionBtn}
                  onClick={() => handleOrderDetail(order)}
                >
                  查看详情
                </button>
                {order.status === '待执行' && (
                  <button 
                    className={`${styles.actionBtn} ${styles.executeBtn}`}
                    onClick={() => handleExecuteOrder(order)}
                  >
                    执行医嘱
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

export default DoctorAdviceOrders
